﻿@page "/"
@rendermode @(new InteractiveServerRenderMode(prerender: false))
@using OpenAI
@using OpenAI.Chat
@inject OpenAIClient aiClient
@inject ILogger<Home> logger
@inject IConfiguration configuration

    <div class="storybox" style="margin: 25%">
        @foreach (var message in chatMessages.OfType<AssistantChatMessage>())
        {
            <p style="font-size: 3em;">@message.Content[0].Text</p>
        }

        <button @onclick="GenerateNextParagraph" autofocus>Generate</button>
    </div>

@code {
    private ChatClient? chatClient = null;
    private List<ChatMessage> chatMessages = new List<ChatMessage>();

    private async Task GenerateNextParagraph()
    {
        if (chatClient == null)
        {
            chatClient = aiClient.GetChatClient(configuration["OpenAI:DeploymentName"] ?? throw new ApplicationException("No OpenAI:DeploymentName."));
            chatMessages.Add(new SystemChatMessage("Pick a random topic and write a sentence of a fictional story about it."));
        }

        if (chatMessages.Count > 1)
        {
            chatMessages.Add(new UserChatMessage("Write the next sentence in the story."));
        }

        var result = await chatClient.CompleteChatAsync(chatMessages);

        chatMessages.Add(new AssistantChatMessage(result.Value.Content[0].Text));

        this.StateHasChanged();
    }

    protected override async Task OnInitializedAsync()
    {
        await GenerateNextParagraph();
        await base.OnInitializedAsync();
    }
}
